<template>
    <el-drawer :show-close="false" :visible.sync="visible" direction="rtl">
        <div class="pd-10 position-relative" style="margin-top: calc(4rem + 4px);height:calc(100% - (4rem + 4px))">
            <div class="flex align-center jus-between map-action">
                <div class="ml-32">
                    <el-autocomplete :fetch-suggestions="searchKeyWord" :trigger-on-focus="false" @select="markerResult" class="inline-input" id="tipinput" placeholder="请输入内容" size="small" v-model="address" value-key="address">
                        <!-- <el-button @click="searchKeyWord" icon="el-icon-search" size="small" slot="append"></el-button> -->
                    </el-autocomplete>
                    <!-- <el-input @keyup.enter.native="searchKeyWord" id="tipinput" placeholder="请输入内容" size="small" style="width:280px;text-indent:8px" v-model="address">
                        <el-button @click="searchKeyWord" icon="el-icon-search" size="small" slot="append"></el-button>
                    </el-input>-->
                </div>
                <div>
                    <el-button @click="submit" round size="mini" type="primary">确认</el-button>
                    <el-button @click="visible=false" round size="mini" type="danger">关闭</el-button>
                </div>
            </div>
            <div class="map height-100b width-100b bg-action" id="container" ref="map"></div>
        </div>
    </el-drawer>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
    data() {
        return {
            visible: false,
            init: false,
            map: null,
            address: '',
            poiList: [],
            search_loading: false,
            choose_address: {},
        }
    },
    watch: {
        visible(value) {
            if (value && !this.init) {
                this.init = true
                this.initAMap()
            }
        },
    },
    mounted() {},
    unmounted() {
       if(this.map){
        this.map.destroy()
       }
    },
    methods: {
        initAMap() {
            let that = this
            AMapLoader.load({
                key: 'b12a94ee6eee16c91d0b316ca14be0b1', // 申请好的Web端开发者Key，首次调用 load 时必填
                securityJsCode: '32e12f1f10a6172559d5217006074b20',
                version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder', 'AMap.CitySearch'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })
                .then((AMap) => {
                    that.map = new AMap.Map('container', {
                        // 设置地图容器id
                        viewMode: '2D', // 是否为3D地图模式
                        zoom: 11, // 初始化地图级别
                    })
                    that.geocoder = new AMap.Geocoder()
                    // this.placeSearchComponent = new AMap.PlaceSearch()
                    that.map.addControl(new AMap.Scale()) // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                    that.map.addControl(new AMap.ToolBar()) //在图面添加鹰眼控件，在地图右下角显示地图的缩略图
                    that.getCurrentLocation()
                    that.handleClick(AMap) //地图选点
                    that.mapSearchInit()
                })
                .catch((e) => {
                    console.log('获取位置错误',e)
                })
        },
        mapSearchInit() {
            let autoOptions = {
                input: 'tipInput',
            }
            this.autoCompleteComponent = new AMap.Autocomplete(autoOptions)
            // 注册placeSearch组件
            this.placeSearchComponent = new AMap.PlaceSearch()
        },
        handleClick() {
            this.map.on('click', (e) => {
                let lng = e.lnglat.lng
                let lat = e.lnglat.lat
                let marker = new AMap.Marker({
                    position: new AMap.LngLat(lng, lat),
                })
                this.map.clearMap() // 清除所有覆盖物（点标志）
                this.map.add(marker) // 添加点标志
                let lnglat = [lng, lat]
                let that = this
                that.geocoder.getAddress(lnglat, function (status, result) {
                    console.log('status, result,lnglat',status, result,lnglat)
                    if (status === 'complete' && result.regeocode) {
                        that.address = result.regeocode.formattedAddress
                        // that.showInfoWindow(marker) //自定义信息窗体
                        that.choose_address = {
                            address: that.address,
                            longitude: lng,
                            latitude: lat,
                            province: result.regeocode.addressComponent.province,
                            city: result.regeocode.addressComponent.city,
                            area: result.regeocode.addressComponent.district,
                        }
                        // let thisPosition =
                        // that.$emit('select', thisPosition) //返回给父组件
                    }else {
                        that.$message.error('根据经纬度查询地址失败')
                    }
                })
            })
        },
        getCurrentLocation() {
            const that = this
            that.geolocation = new AMap.Geolocation({
                timeout: 3000, //超过3秒后停止定位，默认：5s
                enableHighAccuracy: true,
                zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
            })
            that.geolocation.getCurrentPosition(function (status, result) {
                if (status == 'complete') {
                    // that.onComplete(result)
                } else {
                    console.error('result',result)
                  //  that.onError(result) //失败后可使用getCityInfo获取非精准定位（具体到省市）
                }
            })
        },
        searchKeyWord(queryString, cb) {
            let that = this
            that.placeSearchComponent.search(queryString, function (status, result) {
                console.log('status, result',status, result)
                if (status === 'complete') {
                    that.poiList = result.poiList.pois
                    cb(that.poiList)
                } else {
                    that.poiList = []
                    cb(that.poiList)
                }
            })
        },
        markerResult(data) {
            let marker = new AMap.Marker({
                position: new AMap.LngLat(data.location.lng, data.location.lat),
            })
            this.map.clearMap() // 清除所有覆盖物（点标志）
            this.map.add(marker) // 添加点标志
            this.$nextTick(() => {
                this.map.setCenter(data.location)
                this.map.setZoom(15)
            })
            this.choose_address = {
                address: data.name,
                longitude: data.location.lng,
                latitude: data.location.lat,
            }
            // this.showsearchResult = false
            // this.address = data.name
            // var marker = new AMap.Marker({
            //     position: [Number(data.location.lng), Number(data.location.lat)],
            // })
            // this.map.clearMap() // 清除所有覆盖物（点标志）
            // this.map.add(marker) // 添加点标志
            // this.showInfoWindow(marker)
            // setTimeout(() => {
            //     this.map.setCenter(data.location)
            //     this.map.setZoom(15)
            // }, 50)
            // let thisPosition = {
            //     address: this.address,
            //     lng: data.location.lng,
            //     lat: data.location.lat,
            // }
            // this.$emit('select', thisPosition)
        },
        submit() {
            if (!this.choose_address.address) {
                this.$message.waining('您还没有选择地址')
            } else {
                this.$emit('address', this.choose_address)
                this.visible = false
            }
        },
    },
}
</script>

<style lang="scss" scoped>
/deep/.el-drawer__header,
/deep/.el-drawer__header {
    padding: 0;
    margin: 0;
}
.map-action {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 100;
    width: 100%;
}
/deep/#tipinput {
    text-indent: 8px;
    width: 300px;
}
/deep/.el-autocomplete {
    box-shadow: 4px 4px 10px #888888;
}
</style>